import re

from rest_framework import serializers

from experience.models import Experience
from users.constants import TEST


class ExperienceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Experience
        fields = "__all__"
    def validate(self, attrs):

        # 占时不写时间判断
        # if st_time = attrs["s_time"]
        #
        # en_time = attrs["e_time"]
        # if end_time < start_time:
        #     raise serializers.ValidationError("时间大小错误")
        if attrs.get("u_skills"):
            attrs1 = attrs.get("u_skills")

            ret = re.split(r"[;, ]", attrs1)
            # 循环遍历切片的列表，剔除空格
            labels = []
            for skill in ret:
                if skill != " " and skill not in labels:
                    labels.append(skill)

            # 判断用户输入的数据，若是不存在就保错
            for label in labels:
                if label not in TEST:
                    raise serializers.ValidationError("请按照下面的格式和技能表输入")
            labels = ",".join(labels)
            print(self.context["request"].user.id)
            attrs["u_skills"] = labels  # 改变attrs中的u_skills值
            print(attrs)
        return attrs

    def create(self, validated_data):
        # 由于创建信息的表单时候获取不到用户id，所以需要手动添加
        experiences = super().create(validated_data)
        experiences.user_id = self.context["request"].user.id
        experiences.save()
        return experiences
    # todo修改
    # def update(self, instance, validated_data):
    #     id = validated_data.get("id")
    #     experiences = Experience.objects.get(id=id)
    #     return super().update(experiences, validated_data)
